import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
export const useScenarioStore = defineStore('scenario', () => {

  const scenario_list = ref([]);
  const current_scenario = ref(null);



  async function getScenarioList() {
    // eslint-disable-next-line no-async-promise-executor
    await axios.post("http://127.0.0.1:5000/get_scenario_list", {})
      .then(response => {
        scenario_list.value = [];
        for (let i of response.data) {
          i.label = i.name;
          i.value = i.id;
          i.attribute_count = i.attribute_list.length;
          i.image_url = '金针探底.jpg';
          scenario_list.value.push(i);
        }
      })
  }

  async function getScenarioById(id) {
    await axios.post("http://127.0.0.1:5000/get_scenario_by_id", { "id": id })
      .then(response => {
        current_scenario.value = response.data
      })
  }

  async function createScenario(form_data) {
    await axios.post("http://127.0.0.1:5000/create_scenario", form_data, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(
      response => {
      }
    )
  }

  function getDataFileTemplate(filename){
    axios({
      url: 'http://localhost:5000/download/'+filename,
      method: 'GET',
      responseType: 'blob',
    })
    .then((response) => {
      var fileURL = window.URL.createObjectURL(new Blob([response.data]));
      var fileLink = document.createElement('a');

      fileLink.href = fileURL;
      fileLink.setAttribute('download', filename);
      document.body.appendChild(fileLink);

      fileLink.click();
    }
    )
  }

  async function getImageByName(filename){
    let fileURL;
    await axios({
      url: 'http://localhost:5000/image/'+filename,
      method: 'GET',
      responseType: 'blob',
    })
    .then((response) => {
      fileURL = window.URL.createObjectURL(new Blob([response.data]));
    }
    )
    return fileURL.toString();

  }


  
  function addScenarioItem(new_scenario, scenario_id) {
    let form = {
      new_scenario: new_scenario,
      scenario_id: scenario_id
    }
    axios.post("http://127.0.0.1:5000/add_scenario_item", form)
  }
  return { getScenarioList, createScenario, getScenarioById, addScenarioItem,getDataFileTemplate,getImageByName, scenario_list, current_scenario };
}, {
  persist: {
    enabled: true
  }
})
